package cc.magicjson.service.jpa;


import cc.magicjson.entity.User;
//import cc.magicjson.jpa.repository.UserNameRepository;
import cc.magicjson.jpa.repository.UserNameRepository;
import cc.magicjson.jpa.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceJPA {

    private final UserRepository userRepository;
    private final UserNameRepository userNameRepository;

    public UserServiceJPA(UserRepository userRepository, UserNameRepository userNameRepository) {
        this.userRepository = userRepository;
        this.userNameRepository = userNameRepository;
    }

    @Transactional(readOnly = true, transactionManager = "jpaTransactionManager")
    public User findByIdName(String name) {
        return userNameRepository.findByName(name).get(0);
    }

    @Transactional("jpaTransactionManager")
    public void createUser(User user) {
        userRepository.save(user);
    }

    @Transactional(readOnly = true, transactionManager = "jpaTransactionManager")
    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    @Transactional(readOnly = true, transactionManager = "jpaTransactionManager")
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @Transactional("jpaTransactionManager")
    public void updateUser(User user) {
        if (userRepository.existsById(user.getId())) {
            userRepository.save(user);
        }
    }

    @Transactional(transactionManager = "jpaTransactionManager", rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public User saveAndFlush() {
        User user = new User();
        user.setName("name");
        user.setEmail("email");
        userRepository.save(user);
        Optional<User> byId = userRepository.findById(user.getId());
        System.out.println("byId:" + byId);
        return byId.orElseThrow(RuntimeException::new);
    }


    @Transactional("jpaTransactionManager")
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}
